package com.miyu.system.service.book.impl;

import com.alibaba.fastjson2.JSONObject;
import com.miyu.common.utils.magic.GetBeanUtil;
import com.miyu.common.utils.redis.redisUtils.RedisCache;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 书本任务作业
 * @author miyu
 * @date 2022/11/25
 */
public class BookTaskJob implements Callable<Boolean> {
    static RedisCache rdc = GetBeanUtil.getBeanByClass(RedisCache.class);
    private JSONObject params;
    private String key;
    private String type;
    ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(15, new BasicThreadFactory.Builder()
            .namingPattern("saveBookThead-%d").daemon(true).build());

    @Override
    public Boolean call() throws Exception {

        System.out.println("redis");
        System.out.println(Thread.currentThread().getName());
        //初始话 超过10 不再执行 10*10 100秒没有新数据进入不再处理数据
        CheckAndSave(0);
        return null;

    }

    private void CheckAndSave(int num) throws Exception {
        if(rdc.size(key) >0){
           // Thread.sleep(100);
            executorService.submit(new BookSaveTaskJob(rdc.popLeft(key,JSONObject.class),type));
            num=0;
            CheckAndSave(num);
        }else{
            Thread.sleep(10000);
            num=num+1;
            System.out.println("num>>>"+num);
            if(num>=10){
                return;
            }else{
                CheckAndSave(num);
            }
        }
    }


    public BookTaskJob(JSONObject params)  {
        this.key = params.getString("key");
        this.type = params.getString("type");
     }

}
